package com.bb.blog.code.nio;



import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

public class Server {
    public static void main(String[] args) {
        try {
            ServerSocketChannel ssc =  ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ssc.socket().bind(new InetSocketAddress(6000));
            Selector selector = Selector.open();
            ssc.register(selector, SelectionKey.OP_ACCEPT);
//            while(true){
                System.out.println("等待事件发生");

                selector.select();
                System.out.println("有事件发生");

                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while(iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    handle(key);

                }
//            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handle(SelectionKey key) throws IOException {
        if(key.isAcceptable()){
            System.out.println("有客户端链接发生了");
            ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
            SocketChannel sc = ssc.accept();
            sc.configureBlocking(false);
            sc.register(key.selector(),SelectionKey.OP_READ);

        }else if(key.isReadable()){
            System.out.println("有客户断数据可读时间发生了");
            SocketChannel sc = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            int len = sc.read(buffer);
            if(len!=-1){
                System.out.println("读取到了数据" +  new String(buffer.array()));
            }
            ByteBuffer bufferToWrite = ByteBuffer.wrap("Hello Client".getBytes(StandardCharsets.UTF_8));

            sc.write(bufferToWrite);
            key.interestOps(SelectionKey.OP_READ|SelectionKey.OP_WRITE);
//            sc.close();
        }
    }


}
